﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NHibernate;
using FluentValidation;
using FluentValidation.Results;

namespace RevClinic.Core.Commands.Handlers
{
    /// <summary>
    /// Base class for all command handlers. Create implementation of ICommandHandler Handle
    /// method by dividing it into model validation part and main handle action.
    /// </summary>   
    /// <typeparam name="TCommand"></typeparam>
    /// <typeparam name="TModel"></typeparam>
    public abstract class CommandHandlerBase<TCommand, TModel> : ICommandHandler<TCommand>
        where TCommand : ICommand<TModel>
    {
        protected ISessionFactory SessionFactory { get; private set; }

        public CommandHandlerBase(ISessionFactory sessionFactory)
        {
            SessionFactory = sessionFactory;
        }

        protected ISession Session { get { return SessionFactory.GetCurrentSession(); } }

        public void Handle(TCommand command)
        {
            //validate model
            TModel model = command.Model;
            if (model != null) {
                IValidator<TModel> validator = CreateModelValidator();
                validator.ValidateAndThrow(model);
            }
            //run main handle action
            HandleAction(command);
        }

        public abstract IValidator<TModel> CreateModelValidator();
        public abstract void HandleAction(TCommand command);
    }
}
